//
//  POPGestureRecognizeExtension.swift
//  ScreenPoP
//
//  Created by 万孟超 on 2023/3/17.
//  Copyright © 2023 wanmengchao. All rights reserved.
//

import UIKit

extension String {
    /// 十六进制字符串颜色转为UIColor
    /// - Parameter alpha: 透明度
    func color(alpha: CGFloat = 1.0) -> UIColor {
        // 存储转换后的数值
        var red: UInt64 = 0, green: UInt64 = 0, blue: UInt64 = 0
        var hex = self
        // 如果传入的十六进制颜色有前缀，去掉前缀
        if hex.hasPrefix("0x") || hex.hasPrefix("0X") {
            hex = String(hex[hex.index(hex.startIndex, offsetBy: 2)...])
        } else if hex.hasPrefix("#") {
            hex = String(hex[hex.index(hex.startIndex, offsetBy: 1)...])
        }
        // 如果传入的字符数量不足6位按照后边都为0处理，当然你也可以进行其它操作
        if hex.count < 6 {
            for _ in 0..<6-hex.count {
                hex += "0"
            }
        }
        // 分别进行转换
        // 红
        Scanner(string: String(hex[..<hex.index(hex.startIndex, offsetBy: 2)])).scanHexInt64(&red)
        // 绿
        Scanner(string: String(hex[hex.index(hex.startIndex, offsetBy: 2)..<hex.index(hex.startIndex, offsetBy: 4)])).scanHexInt64(&green)
        // 蓝
        Scanner(string: String(hex[hex.index(startIndex, offsetBy: 4)...])).scanHexInt64(&blue)
        return UIColor(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: alpha)
    }
     
     /// RGB字符串转换为颜色 "255,255,255"或"255"，如果只有两个蓝色默认为0
     /// - Parameter alpha: alpha值
     /// - Returns: 颜色
     func rgbColor(alpha: CGFloat = 1.0) -> UIColor {
         let colorArray = components(separatedBy: ",")
         var red : CGFloat = 0,green : CGFloat = 0, blue : CGFloat = 0
         if colorArray.count == 3 {
             red = CGFloat(Int(colorArray[0])!)
             green = CGFloat(Int(colorArray[1])!)
             blue = CGFloat(Int(colorArray[2])!)
         }else if colorArray.count == 2 {
             red = CGFloat(Int(colorArray[0])!)
             green = CGFloat(Int(colorArray[1])!)
         }else if colorArray.count == 1 {
             red = CGFloat(Int(colorArray[0])!)
             green = CGFloat(Int(colorArray[0])!)
             blue = CGFloat(Int(colorArray[0])!)
         }
        return UIColor(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: alpha)
     }
     
}


extension UIImage {
    func imageColor(_ color: UIColor) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        let context = UIGraphicsGetCurrentContext()
        context?.translateBy(x: 0, y: size.height)
        context?.scaleBy(x: 1.0, y: -1.0)
        context?.setBlendMode(.normal)
        let rect = CGRect(origin: .zero, size: size)
        context?.clip(to: rect, mask: cgImage!)
        color.setFill()
        context?.fill(rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage ?? self
    }
}
